<script setup lang="ts" name="SystemSmsTemplateSendForm">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { SmsTemplateApi, SendSmsReqType } from '@/api/system/messages/sms/template'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  content: '',
  mobile: '',
  params: [],
  templateParams: new Map(),
  templateCode: ''
})
const formRules = reactive({
  mobile: [{ required: true, message: t('sys.messages.sms.template.rules', 'mobile'), trigger: 'blur' }],
  templateParams: {}
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id: number) => {
  resetForm()
  // 修改时，设置数据
  formLoading.value = true
  try {
    const data = await SmsTemplateApi.detail(id)
    // 设置动态表单
    formData.value.content = data.content
    formData.value.params = data.params
    formData.value.templateCode = data.code
    formData.value.templateParams = data.params.reduce((obj, item) => {
      obj[item] = '' // 给每个动态属性赋值，避免无法读取
      return obj
    }, {})
    formRules.templateParams = data.params.reduce((obj: any, item) => {
      obj[item] = { required: true, message: t('sys.messages.sms.template.rules', 'paramEmpty', [item]), trigger: 'blur' }
      return obj
    }, {})
  } finally {
    formLoading.value = false
    visible.value = true
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SendSmsReqType
    const logId = await SmsTemplateApi.send(data)
    if (logId) {
      message.success(t('sys.messages.sms.template', 'sendDone', [logId]))
    }
    visible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    content: '',
    mobile: '',
    params: [],
    templateParams: new Map(),
    templateCode: ''
  }
  formRules.templateParams = {}
  formRef.value?.resetFields()
}
</script>

<template>
  <Dialog v-model="visible" :title="t('sys.messages.sms.template', 'send')" height="280px" type="scroll" width="720">
    <el-form ref="formRef" v-loading="formLoading && systemConfig.loadingType === 'module'" :model="formData" label-position="top" :rules="formRules">
      <el-form-item :label="t('sys.messages.sms.template', 'content')" prop="content">
        <el-input v-model="formData.content" :placeholder="t('sys.messages.sms.template.rules', 'content')" clearable readonly type="textarea" />
      </el-form-item>
      <el-form-item :label="t('sys.messages.sms.template', 'mobile')" prop="mobile">
        <el-input v-model="formData.mobile" :placeholder="t('sys.messages.sms.template.rules', 'mobile')" clearable />
      </el-form-item>
      <el-form-item v-for="param in formData.params" :key="param" :label="t('sys.messages.sms.template', 'param', [param])" :prop="'templateParams.' + param">
        <el-input v-model="formData.templateParams[param]" :placeholder="t('sys.messages.sms.template.rules', 'param', [param])" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">{{ t('action', 'cancel') }}</el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">{{ t('action', 'confirm') }}</el-button>
    </template>
  </Dialog>
</template>

<style scoped lang="scss">
.el-form {
  margin-right: -6px;
}

.el-form-group {
  display: flex;
  flex: 1;

  .el-form-item {
    flex: 1;
    margin: 0;
  }

  .el-form-item+.el-form-item {
    margin: 0;
  }
}

.el-form-item+.el-form-item {
  margin-top: 12px;
}
</style>
